package org.shuma.goods.interceptor;

import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding;
import com.google.gson.JsonObject;
import org.shuma.user.facade.UserFacade;
import org.shuma.user.utils.HttpCodeEnum;
import org.shuma.user.utils.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author : liuming
 * @date : 2024/6/18 上午7:49
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @SofaReference(interfaceType = UserFacade.class, binding = @SofaReferenceBinding(bindingType = "bolt"), uniqueId = "${service.user.unique.id}")
    private UserFacade userFacade;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (Objects.isNull(authorization) || Objects.isNull(userFacade.getUserInfoByToken(authorization).getData())) {
            response.setContentType("application/json");
            Result<String> result = new Result<>();
            result.error(HttpCodeEnum.NEED_LOGIN, "");
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("code", HttpCodeEnum.NEED_LOGIN.getCode());
            jsonObject.addProperty("message", HttpCodeEnum.NEED_LOGIN.getMsg());
            jsonObject.addProperty("description", "");
            OutputStream ps = response.getOutputStream();
            //这句话的意思，使得放入流的数据是utf8格式
            ps.write(String.valueOf(jsonObject).getBytes(StandardCharsets.UTF_8));
//            response.getWriter().write();
            return false;
        } else {
            request.setAttribute("userInfo", userFacade.getUserInfoByToken(authorization).getData());
            return true;
        }

    }
}
